
package com.cinyi.ormlite.core;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.cinyi.ormlite.annotation.AnnotationNotFoundException;
import com.cinyi.ormlite.annotation.TField;
import com.cinyi.ormlite.annotation.TOne2many;
import com.cinyi.ormlite.annotation.TTable;

public class TableConfigCache
{
    private static final Map<String,TableConfig> configs = new ConcurrentHashMap<String, TableConfig>();
    
    private TableConfigCache()
    {}
    
    public synchronized static TableConfig getConfig(Class<?> clazz) throws AnnotationNotFoundException{
        if (!clazz.isAnnotationPresent(TTable.class)) {
            throw new AnnotationNotFoundException(clazz.getName() + " is not Entity Annotation.");
        }
        if(configs.containsKey(clazz.getName())){
            return configs.get(clazz.getName());
        }else{
            //获得表名
            String tableName = getTableName(clazz);
            TTable tTable = clazz.getAnnotation(TTable.class);
            
            Field[] fields = clazz.getDeclaredFields();
            TableConfig cfg = new TableConfig(tableName);
            for (Field field : fields) {
                String propertyName = field.getName();
                if (field.isAnnotationPresent(TField.class)) {
                    TField tfield = field.getAnnotation(TField.class);
                    if(tfield.constrains().primaryKey()){
                        cfg.setIdProperty(propertyName);
                        cfg.setIdColumnName(tfield.name());
                    }
                    
                }else  if (field.isAnnotationPresent(TOne2many.class)) {
                    TOne2many o2m = field.getAnnotation(TOne2many.class);
                    if(o2m.lazy())
                        cfg.getOne2many().add(field);
                }
            }
            
            cfg.setFields(fields);
            cfg.setCrazyload(tTable.crazyload());
            
            configs.put(clazz.getName(), cfg);
            
            return cfg ;
        }
    }
 
    private static String getTableName(Class<?> clazz) throws AnnotationNotFoundException {
        if (clazz.isAnnotationPresent(TTable.class)) {
            TTable entity = clazz.getAnnotation(TTable.class);
            if(entity==null||"".equals(entity.value())){
                return clazz.getSimpleName().replaceAll("\\.", "_").toLowerCase() ;
            }else
                return entity.value();
        } else {
            throw new AnnotationNotFoundException(clazz.getName() + " is not Entity Annotation.");
        }
    }
    
}
